<template>
  <div>
    <a-modal
      :visible="visible"
      :maskClosable="false"
      :keyboard="!formModal.loading"
      :closable="!formModal.loading"
      :title="modalTitle"
      :okText="'提交'"
      width="860px"
      :destroyOnClose="true"
      @cancel="cancelSub"
    >
      <!-- centered -->

      <a-form-model class="flex-model-form"
        ref="addForm"
        :model="formModal.form"
        :rules="formModal.rules"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="组织名称" prop="youthOrgName">
              <a-input placeholder="请输入组织名称" v-model="formModal.form.youthOrgName" allow-clear />
            </a-form-model-item>
         </a-col>
          <a-col :span="12">
            <a-form-model-item label="上级组织" prop="parentName">
              <a-input placeholder="" v-model="formModal.form.parentName" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="组织类型" prop="orgType">
              <LeagueLevelSelect v-model="formModal.form.orgType"
                placeholder="请选择组织类型"
                :autoSelect="modalType=='add'"
                :params="orgTypeParams"
              >
              </LeagueLevelSelect>
              <!-- <a-input placeholder="请选择组织类型" v-model="formModal.form.type" allow-clear /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="组织成立时间" prop="orgRegtime">
              <a-date-picker 
                placeholder="请选择组织成立时间"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                v-model="formModal.form.orgRegtime"
                allow-clear 
               />
              <!-- <a-input /> -->
            </a-form-model-item>
          </a-col>
        </a-row>
        <template v-if="modalType!=='add'">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="组织书记" prop="orgSecretary">
                <SelectMember v-model="formModal.form.orgSecretary"
                  :dataList="memberListData"
                  labelInValue
                  placeholder="请选择组织书记"
                >
                </SelectMember>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="组织副书记">
                <SelectMember v-model="formModal.form.deputySecretary"
                  :dataList="memberListData"
                  labelInValue
                  mode="multiple"
                  placeholder="请选择组织副书记"
                >
                </SelectMember>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="管理人员" prop="manager">
                <SelectMember v-model="formModal.form.manager"
                  :dataList="memberListData"
                  labelInValue
                  mode="multiple"
                  placeholder="请选择管理人员"
                >
                </SelectMember>
              </a-form-model-item>
            </a-col>
            <a-col v-if="modalType == 'change'" :span="12">
              <a-form-model-item label="换届时间" prop="transitionTime">
                <a-date-picker
                  placeholder="请选择换届时间"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  v-model="formModal.form.transitionTime"
                  allow-clear 
                 />
              </a-form-model-item>
            </a-col>
          </a-row>
        </template>
      </a-form-model>
      
      <template v-if="modalType!=='add'">
        <AddPerson
          :orgType="formModal.form.orgType"
          :committeeList.sync="committeeList"
        ></AddPerson>
      </template>
      
      <template slot="footer">
        <a-button :disabled="formModal.loading" key="back" @click="cancelSub">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="formModal.loading" @click="submitForm">
          提交
        </a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>

import { STable } from '@/components' // 表格
import { annualPlanAdd } from '@/api/office/anualConference/index'
import LeagueLevelSelect from '../../componments/leagueLevelSelect.vue'
import SelectMember from '../../componments/employeeSelect.vue'
import AddPerson from './addperson.vue'
import { insertSelective, getYouthOrganizationById, updateByPrimaryKeySelective, queryAllYouthMemberList } from '@/api/partyMasses/leagueManage'
export default {
    name:'a'+ Date.now(),
    // name: 'AddPartyOrg',
    components: {
      LeagueLevelSelect,
      SelectMember,
      AddPerson,
      STable
    },
    props: {
      modalType: {
        type: String,
        default() {
          return 'add'
        }
      },
      visible: {
        type: Boolean,
        default() {
            return true
        }, 
      },
      selectOptions: {
        type: Object,
        default() {
          return {}
        }
      },
      curId: {
        type: String,
        default() {
          return ''
        }
      }
    },
    data() {
        return {
          memberListData: [],
          formModal: {
            loading: false,
            form: {
              youthOrgName: '',//党组织名称
              parentId: '',//父级id
              orgType: '',//组织类型
              orgRegtime: '',//成立时间
              parentName: '',
              
              orgSecretary: '',
              deputySecretary: [],
              manager: [],
              transitionTime: ''
            },
            rules: {
              youthOrgName: [ { required: true, message: '请输入组织名称', trigger: 'blur' } ],
              // parentId: [ { required: true, message: '请选择编制单位', trigger: 'change' } ],
              orgType: [ { required: true, message: '请选择组织类型', trigger: 'blur' } ],
              orgRegtime: [ { required: true, message: '请选择组织成立时间', trigger: 'change' } ],
              orgSecretary: [ { required: true, message: '请选择组织书记', trigger: 'change' } ],
              manager: [ { required: true, message: '请选择管理人员', trigger: 'change' } ],
              transitionTime: [ { required: true, message: '请选择换届时间', trigger: 'change' } ],
            },
          },
          committeeList: []
        }
    },
    computed: {
      modalTitle() {
        const map = {
          add: '新增团组织信息',
          edit: '组织信息设置',
          change: '换届'
        }
        return map[this.modalType]
      },
      orgTypeParams() {
        if (this.modalType == 'add') {
          return { id: this.selectOptions.id }
        } else {
          return { orgId: this.curId }
        }
      }
    },
    watch: {
      visible(val) {
        this.$refs.addForm && this.$refs.addForm.resetFields();
        if (val) {
          if (this.modalType == 'add') {
            this.formModal.form.parentId = this.selectOptions?.id;
            this.formModal.form.parentName = this.selectOptions?.youthOrgName;
            this.formModal.form.orgRegtime = this.$dateFormat(new Date(), 'D')
          } else {
            this.getDetail();
            // this.queryMemberSelectData();
          }
        }
      }
    },
    mounted() {
    },
    methods: {
      queryMemberSelectData() {
        // 获取下拉框列表
        queryAllYouthMemberList({}).then((res) => {
            const dataList = res.data || [];
            this.memberListData = dataList
        })
        .catch((res) => {
        })
      },
      getDetail() {
        this.committeeList = [];
        this.formModal.form.deputySecretary = []
        getYouthOrganizationById({id: this.curId}).then((res) => {
          if (res && res.code == 0) {
              const datas = res.data;
              this.formModal.form.youthOrgName = datas.youthOrgName;//党组织名称
              this.formModal.form.parentId = datas.parentId;//父级id
              this.formModal.form.orgType = datas.orgType;//组织类型
              this.formModal.form.orgRegtime = datas.orgRegtime;//成立时间
              this.formModal.form.parentName = datas.parentName;
              
              this.formModal.form.orgSecretary = this.changeToSelect(datas.managerList, 1)//datas.orgSecretaryId;
              this.formModal.form.deputySecretary = this.changeToSelect(datas.managerList, 2);
              this.formModal.form.manager = this.changeToSelect(datas.managerList, 3);
              this.formModal.form.transitionTime = datas.transitionTime || this.$dateFormat(new Date(), 'D');;
              // const orgSecretary = this.changeToSelect(datas.managerList, 1)
              // console.log(orgSecretary)
              // this.changeToSelect(datas.managerList, 1)
              
              this.committeeList = datas.committeeList;
          }
        })
      },
      changeToSelect(list, type) {
        const result = list.filter((item, index) => {
          return (item.type == type)
        }).map((item, index) => {
          let obj = {
            key: item.userId,
            label: item.userName
          }
          return obj;
        })
        return type == 1 ? result[0] : result;
      },
      cancelSub() {
        let _this = this;
        _this.$emit('update:visible', false)
      },
      submitForm() {
        this.$refs.addForm.validate(valid => {
          if (valid) {
            
            if (this.modalType == 'add') {
              this.confirmSub('确定提交吗？', this.insertSelective)
            } else if (this.modalType == 'edit' || this.modalType == 'change') {
              const validateComi = this.committeeList.some((item, index) => {
                return (!item.userId) || (!item.userName)
              })
              if (validateComi) {
                this.$message.error('请先选择委员！')
                return
              }
              this.confirmSub('确定提交吗？', this.update)
            }
          } else {
            return false;
          }
        });
      },
      changeList(list, type) {
        const result = list.map((item, index) => {
          const obj = {
            type: type,
            youthOrgId: this.curId,
            userId: item.key || item.userId,
            userName: item.label || item.userName
          }
          if (item.youthPost) obj.youthPost = item.youthPost;
          if (item.phone) obj.phone = item.phone;
          if (item.employeeNum) obj.employeeNum = item.employeeNum;
          return obj;
        })
        return result
      },
      update() {
        // type 管理类型（1、组织书记，2、组织副书记，3、管理人员，4：党委委员）
        const orgSecretary = this.changeList([this.formModal.form.orgSecretary], 1);
        const deputySecretary = this.changeList(this.formModal.form.deputySecretary, 2);
        const manager = this.changeList(this.formModal.form.manager, 3);
        const committee = this.changeList(this.committeeList, 4)
        let managerList = [].concat(orgSecretary, deputySecretary, manager, committee)
        
        const params = {
          id: this.curId,
          managerList: managerList,
          orgType: this.formModal.form.orgType,
          youthOrgName: this.formModal.form.youthOrgName,
          orgRegtime: this.formModal.form.orgRegtime,
          orgSecretary: this.formModal.form.orgSecretary?.label,
          parentName: this.formModal.form.parentName
        }
        if (this.modalType == 'change') params.transitionTime = this.formModal.form.transitionTime;
        this.formModal.loading = true;
        return updateByPrimaryKeySelective(params).then((res) => {
          this.$refs.addForm.resetFields()
          this.formModal.loading = false
          if ((res && res.data && res.data.code == 0) || (res && res.code == 0)) {
            this.$message.success('设置成功');
            this.$emit('submitSuccess');
            this.cancelSub();
          } else {
            this.$message.error('设置组织信息失败！')
          }
        }).catch(() => {
          this.formModal.loading = false
        })
      },
      insertSelective() {
        const params = {
          orgStatus: 1,
          youthOrgName: this.formModal.form.youthOrgName,//党组织名称
          parentId: this.formModal.form.parentId,//父级id
          orgType: this.formModal.form.orgType,//组织类型
          orgRegtime: this.formModal.form.orgRegtime,//成立时间
        }
        this.formModal.loading = true;
        return insertSelective(params).then((res) => {
          this.$refs.addForm.resetFields()
          this.formModal.loading = false
          if ((res && res.data && res.data.code == 0) || (res && res.code == 0)) {
            this.$message.success('新增成功')
            this.formModal.form.parentName = '';
            this.$emit('submitSuccess');
            this.cancelSub();
          } else {
            this.$message.error('新增失败！')
          }
        }).catch(() => {
          this.formModal.loading = false
        })
      },
      confirmSub(text,func) {
        let _this = this;
        this.$confirm({
          title: '温馨提示',
          content: text,
          onOk:() => {
            return func()
          },
          onCancel() {
          },
        });
      }
    },
}
</script>
<style lang="less" scoped>
  .ant-form-item{
    display: flex;
  }
  .tool-btns .ant-btn{
    margin-left: 12px;
   }
</style>